import { createStore } from "vuex";

const store = createStore({
    state: {
		user: {}, // 用户信息
		carts: [], // 购物车
		token: '', // token
		configs: [], // 项目全局配置
		inviter: 0, // 邀请人ID
		isLeader: false, // 是否是团长
		leaderId: 0, // 团长ID
		hasShop: false, // 是否拥有店铺
		franchisee_id: 0, // 代理商？
		withDrawInfo: null,
	},
	getters: {
	    inviter: state => {
	      return state.inviter;
	    },
	    isLeader: state => {
	      return state.isLeader;
	    },
		configs: state => {
		  return state.configs;
		},
		carts: state => {
		  return state.carts;
		},
		user: state => {
		  return state.user;
		},
		leaderId: state => {
			return state.leaderId
		},
		hasShop: state => {
			return state.hasShop
		},
		franchisee_id: state => {
			return state.franchisee_id
		},
		payCarts: state => {
		  return state.payCarts;
		},
		withDrawInfo: state => {
			return state.withDrawInfo;
		}
	  },
	mutations: {
	    setToken(state, token) {
	      state.token = token;
	    },
		setCartBadge(state) {
			const cartsJson = uni.getStorageSync('carts');
			let carts = [];
			if (cartsJson !== "") {
				carts = JSON.parse(cartsJson)
			}
			const length = carts.filter((c) => c.count > 0).length;
			const pages = getCurrentPages()
			const showBadge = pages.filter((p) => {
						  const ps = p.path || p.route
				return ps === "pages/index/index" || ps === "pages/cart/index" || ps === "pages/my/index" || ps === "pages/category/index"
			}).length > 0
			if (showBadge) {
			  if (length > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: String(length)
				})
			  } else {
				uni.removeTabBarBadge({
					index: 2
				});
			  }
			}
		},
	    setCarts(state, carts) {
	      state.carts = carts;
		  uni.setStorageSync('carts', JSON.stringify(carts));
	    },
	    setConfigs(state, configs) {
	      state.configs = configs;
	    },
	    setUser(state, user) {
	      state.user = user;
	    },
		setInviter(state, inviter) {
			state.inviter = inviter;
		},
		setIsLeader(state, isLeader) {
			state.isLeader = isLeader
		},
		setLeaderId(state, name) {
			state.leaderId = name;
		},
		setHasShop(state, name) {
			state.hasShop = name;
		},
		setFranchisee(state, name) {
			state.franchisee_id = name
		},
		setPayCarts(state, name) {
			state.payCarts = name;
		},
		setWithDrawInfo(state, name) {
			state.withDrawInfo = name;
		}
	}
})

export default store;